# -*- coding: utf8 -*-

import traceback
from time import sleep, time
import os
from subprocess import Popen
from multiprocessing import Process

from worker import Worker
from archive import Archive, which
from images import is_image
from worker.image import ImageTaskManager

class ArchiveWorker( Worker ):

    my_query_name = "archives"

    def run ( self ):
        
        print("ArchiveWorker: START: %s" % self.my_query_name)

        bin_rm = which("rm")

        p = self.app.get_project()

        while not self.stop_event.isSet():

            try:
                data = self.app.get_queue(self.my_query_name).get_nowait()
            except:
                data = None

            if data is None:
                sleep(0.01)
                continue

            file_id, file_path, mime = data

            try:
                self.app.get_stats().set_imaging(file_path, 0, 0, time() )

                tmp_dir = os.tempnam()
                if not os.path.isdir(tmp_dir):
                    os.makedirs(tmp_dir)

                arch = Archive(file_path, mime)

                p_extract = Process( target=arch.extract_files, args = (tmp_dir,))
                p_extract.start()
                while p_extract.is_alive():
                    sleep(0.01)
                    if self.stop_event.isSet():
                        p_extract.terminate()
                        break

                manager = ImageTaskManager()

                for root, dirs, files in os.walk(tmp_dir):

                    if self.stop_event.isSet():
                        break

                    self.app.get_stats().set_imaging(file_path, len(files), 0, time() )

                    for f in files:

                        if self.stop_event.isSet():
                            break

                        full_path = os.path.join(root, f)

                        if is_image(full_path):
                            manager.add_task((file_id, full_path, tmp_dir,))

                    manager.run(self.app)

                    while not manager.check():
                        sleep(0.01)
                        if self.stop_event.isSet():
                            break

                    if self.stop_event.isSet():
                        manager.stop().wait()

                ret = Popen([bin_rm,"-rf", tmp_dir]).wait()

            except Exception, e:
                self.app.get_stats().inc("errors_count", 1)
                print("ArchiveWorker: ERROR!\n%s" % traceback.format_exc())
                pass

            self.app.get_stats().inc("archives_processed", 1)

            self.app.get_queue(self.my_query_name).task_done()

            p.close_session()

        print("ArchiveWorker: STOP: %s" % self.my_query_name)

        self.stop_event.clear()
        return
